import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/auth'
import Login from '@/views/login/index.vue'
import Layout from '@/layout/index.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/index',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: '/home',
        component: () => import('@/views/home/index.vue')
      }
    ]
  },
  {
    path: '/users',
    component: Layout,
    children: [
      {
        path: '/users',
        component: () => import('@/views/users/index.vue')
      }
    ]
  },
  {
    path: '/permissions',
    component: Layout,
    redirect: '/roles',
    children: [
      {
        path: '/roles',
        component: () => import('@/views/permissions/roles.vue')
      },
      {
        path: '/rights',
        component: () => import('@/views/permissions/right.vue')
      }
    ]
  },
  {
    path: '/goods',
    component: Layout,
    children: [
      {
        path: '/goods',
        component: () => import('@/views/shopping/goods.vue')
      },
      {
        path: '/params',
        component: () => import('@/views/shopping/params.vue')
      },
      {
        path: '/categories',
        component: () => import('@/views/shopping/shopp.vue')
      }
    ]
  },
  {
    path: '/orders',
    component: Layout,
    children: [
      {
        path: '/orders',
        component: () => import('@/views/orders/index.vue')
      }
    ]
  },
  {
    path: '/reports',
    component: Layout,
    children: [
      {
        path: '/reports',
        component: () => import('@/views/data/index.vue')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    next()
  }
  const token = getToken('Admin-Token')
  if (!token) {
    next('/login')
  }
  next()
})

export default router
